package com.ktg.mes.wm.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.constant.UserConstants;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.md.domain.MdItem;
import com.ktg.mes.md.service.IMdItemService;
import com.ktg.mes.pro.domain.ProItemNeed;
import com.ktg.mes.pro.domain.ProTask;
import com.ktg.mes.pro.service.IProItemNeedService;
import com.ktg.mes.pro.service.IProTaskService;
import com.ktg.mes.wm.domain.*;
import com.ktg.mes.wm.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.utils.poi.ExcelUtil;
import com.ktg.common.core.page.TableDataInfo;

/**
 * 生产领料单行Controller
 *
 * @author yinjinlu
 * @date 2022-07-14
 */
@RestController
@RequestMapping("/mes/wm/issueline")
public class WmIssueLineController extends BaseController
{
    @Autowired
    private IWmIssueLineService wmIssueLineService;

    @Autowired
    private IProItemNeedService proItemNeedService;

    @Autowired
    private IWmWarehouseService wmWarehouseService;



    /**
     * 查询生产领料单行列表
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueline:list')")
    @GetMapping("/list")
    public TableDataInfo list(WmIssueLine wmIssueLine)
    {
        startPage();
        List<WmIssueLine> list = wmIssueLineService.selectWmIssueLineList(wmIssueLine);
        return getDataTable(list);
    }


    /**
     * 查询生产领料单行列表
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueline:list')")
    @GetMapping("/groupList")
    public TableDataInfo groupList(WmIssueLine wmIssueLine)
    {
        startPage();
        QueryWrapper<WmIssueLine> queryWrapper = new QueryWrapper<>(wmIssueLine);
        queryWrapper.select(" dist");
        queryWrapper.orderByDesc("line_id");
        List<WmIssueLine> list =  wmIssueLineService.list(queryWrapper);;
        return getDataTable(list);
    }


    /**
     * 查询生产领料单行列表
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueline:list')")
    @GetMapping("/listOnly")
    public TableDataInfo listOnly(WmIssueLine wmIssueLine)
    {
        Page<WmIssueLine> page = new Page<>(wmIssueLine.getPage(),wmIssueLine.getPageCount());
        QueryWrapper<WmIssueLine> queryWrapper = new QueryWrapper<>(wmIssueLine);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.ge("create_time", DateUtils.getDateByAddSecond(-3*30*24*3600));
        IPage iPage = wmIssueLineService.page(page,queryWrapper);
        return getDataTable(iPage);
    }

    /**
     * 导出生产领料单行列表
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueline:export')")
    @Log(title = "生产领料单行", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmIssueLine wmIssueLine)
    {
        List<WmIssueLine> list = wmIssueLineService.selectWmIssueLineList(wmIssueLine);
        ExcelUtil<WmIssueLine> util = new ExcelUtil<WmIssueLine>(WmIssueLine.class);
        util.exportExcel(response, list, "生产领料单行数据");
    }

    /**
     * 获取生产领料单行详细信息
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueline:query')")
    @GetMapping(value = "/{lineId}")
    public AjaxResult getInfo(@PathVariable("lineId") Long lineId)
    {
        return AjaxResult.success(wmIssueLineService.selectWmIssueLineByLineId(lineId));
    }

    /**
     * 新增生产领料单行
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueline:add')")
    @Log(title = "生产领料单行", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody WmIssueLine wmIssueLine)
    {
        if(StringUtils.isEmpty(wmIssueLine.getWarehouseCode())){
            WmWarehouse warehouse = wmWarehouseService.getById(wmIssueLine.getWarehouseId());
            warehouse.setWarehouseCode(warehouse.getWarehouseCode());
            warehouse.setWarehouseName(warehouse.getWarehouseName());
        }

        return toAjax(wmIssueLineService.insertWmIssueLine(wmIssueLine));
    }

    /**
     * 修改生产领料单行
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueline:edit')")
    @Log(title = "生产领料单行", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody WmIssueLine wmIssueLine)
    {
        if(StringUtils.isEmpty(wmIssueLine.getWarehouseCode())){
            WmWarehouse warehouse = wmWarehouseService.getById(wmIssueLine.getWarehouseId());
            warehouse.setWarehouseCode(warehouse.getWarehouseCode());
            warehouse.setWarehouseName(warehouse.getWarehouseName());
        }
        return toAjax(wmIssueLineService.updateWmIssueLine(wmIssueLine));
    }

    /**
     * 删除生产领料单行
     */
    @PreAuthorize("@ss.hasPermi('mes:wm:issueline:remove')")
    @Log(title = "生产领料单行", businessType = BusinessType.DELETE)
	@DeleteMapping("/{lineIds}")
    public AjaxResult remove(@PathVariable Long[] lineIds)
    {
        return toAjax(wmIssueLineService.deleteSQLIds(lineIds));
    }

    /**
     * 获取 备货数量
     */
    @GetMapping(value = "/stockOutCount")
    public AjaxResult stockOutCount(@RequestParam(name="itemNeedId") Long itemNeedId)
    {
        if (itemNeedId == null){
            return AjaxResult.error("客户需求不能为空");
        }

        ProItemNeed proItemNeed = proItemNeedService.getById(itemNeedId);


        WmIssueLine wmIssueLine = new WmIssueLine();
        wmIssueLine.setOutType("备货");
        wmIssueLine.setItemNeedId(itemNeedId);

        QueryWrapper queryWrapper = new QueryWrapper<>(wmIssueLine);
        queryWrapper.select("sum(quantity) as quantity,item_need_id");
        queryWrapper.groupBy("item_need_id");
        WmIssueLine wmIssueLine1 = wmIssueLineService.getOne(queryWrapper);

        Map<String,BigDecimal> floatMap = new HashMap<>();
        if (wmIssueLine1 != null && wmIssueLine1.getQuantity() != null){
            floatMap.put("quantity",wmIssueLine1.getQuantity());
        }else {
            floatMap.put("quantity",new BigDecimal(0));
        }
        floatMap.put("quantityAll",BigDecimal.valueOf(proItemNeed.getNeedCount().intValue()));

        return AjaxResult.success(floatMap);
    }


}
